﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
using ClosedXML.Excel;
using Microsoft.AnalysisServices;

namespace CubeTranslationExtractor
{
    public partial class MainForm : Form
    {
        private Server _olapServer;
        private TranslationDataTable _translationDataTable;
        private string defaultLanguage;
        public MainForm()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            dbTreeview.CanExpandGetter += model => model is Server;
            dbTreeview.ChildrenGetter += model =>
            {
                Server srv = model as Server;
                return srv != null ? srv.Databases : null;
            };
        }

        private void StartProgress()
        {
            toolStripProgressBar.Style = ProgressBarStyle.Marquee;
            toolStripProgressBar.Minimum = 0;
            toolStripProgressBar.Maximum = 100;
            toolStripProgressBar.Value = 0;
        }

        private void EndProgress()
        {
            toolStripProgressBar.Style = ProgressBarStyle.Continuous;
            toolStripProgressBar.Value = 100;
        }

        private void OnConnectClicked(object sender, EventArgs e)
        {
            BackgroundWorker bwrk = new BackgroundWorker();
            bwrk.DoWork += (o, args) =>
            {
                _olapServer = new Server();
                _olapServer.Connect(string.Format("Provider=MSOLAP;Data Source={0};", toolStripTbxName));
            };
            bwrk.RunWorkerCompleted += (o, args) =>
            {
                if (args.Error != null)
                {
                    MessageBox.Show(args.Error.Message, @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    StatusBarConnectionState.Text = @"Disconnected";
                }
                StatusBarConnectionState.Text = @"Connected";
                toolStripBtnConnect.Enabled = false;
                toolStripTbxName.Enabled = false;
                toolStripBtnTranslate.Enabled = true;
                toolStripBtnExcelExport.Enabled = true;
                StatusBarConnectionState.ForeColor = Color.Green;

                dbTreeview.Roots = new[] {_olapServer};

                EndProgress();
            };
            StartProgress();
            bwrk.RunWorkerAsync();
        }

        private void OnTranslateClicked(object sender, EventArgs e)
        {
            _translationDataTable = new TranslationDataTable();
            StartProgress();
            BackgroundWorker wrk = new BackgroundWorker();
            wrk.DoWork += (o, args) =>
            {
                ArrayList arrayList = args.Argument as ArrayList;
                var dbs = arrayList != null
                    ? arrayList.ToArray().OfType<Database>()
                    : _olapServer.Databases.OfType<Database>();

                foreach (Database olapDatabase in dbs)
                {
                    CultureInfo _mc = new CultureInfo(olapDatabase.Language);
                    defaultLanguage = _mc.DisplayName;
                    // Cube 
                    foreach (Cube cube in olapDatabase.Cubes)
                    {
                        ////Measure Group 
                        foreach (MeasureGroup olapMeasureGroup in cube.MeasureGroups)
                        {
                            _translationDataTable.AddTranslation("MeasureGroup" + " - " + cube.Name,
                                olapMeasureGroup.Name,
                                cube.Language,
                                olapMeasureGroup.Translations);

                            // Measures 
                            foreach (Measure olapMeasure in olapMeasureGroup.Measures)
                            {
                                _translationDataTable.AddTranslation("Measure" + " - " + olapMeasureGroup.Name,
                                    olapMeasure.Name, cube.Language,
                                    olapMeasure.Translations);
                            }

                            // Measure Group Dimension 
                            foreach (MeasureGroupDimension olapMeasureGroupDimension in olapMeasureGroup.Dimensions)
                            {
                                _translationDataTable.AddTranslation("MeasureGroup Dimension" + " - " + cube.Name,
                                    olapMeasureGroupDimension.CubeDimension.Name,
                                    cube.Language,
                                    olapMeasureGroupDimension.CubeDimension
                                        .Translations);
                            }
                        }
                        //Cube Dimension 
                        foreach (CubeDimension cubeDimension in cube.Dimensions)
                        {
                            _translationDataTable.AddTranslation("Dimension - " + cube.Name,
                                cubeDimension.Dimension.Name,
                                cubeDimension.Dimension.Language,
                                cubeDimension.Translations);

                            //Dimension Attribute 
                            foreach (CubeAttribute olapDimAttribute in cubeDimension.Attributes)
                            {
                                _translationDataTable.AddTranslation("Attribute - " + cubeDimension.Name,
                                    olapDimAttribute.Attribute.Name,
                                    cubeDimension.Dimension.Language,
                                    olapDimAttribute.Attribute.Translations);
                            }


                            ////Dimension Hierarchy 
                            foreach (CubeHierarchy olapDimHierarchy in cubeDimension.Hierarchies)
                            {
                                _translationDataTable.AddTranslation("Hierarchy - " + cubeDimension.Name,
                                    olapDimHierarchy.Hierarchy.Name,
                                    cubeDimension.Dimension.Language,
                                    olapDimHierarchy.Hierarchy.Translations);
                                //Dimension Hierarchy Level 
                                foreach (Level olapDimHierachyLevel in olapDimHierarchy.Hierarchy.Levels)
                                {
                                    _translationDataTable.AddTranslation(
                                        "Hierarchy Attribute - " + cubeDimension.Name,
                                        olapDimHierachyLevel.Name,
                                        cubeDimension.Dimension.Language,
                                        olapDimHierachyLevel.Translations);
                                }
                            }
                        }
                    }
                }
            };
            wrk.RunWorkerCompleted += (o, args) =>
            {
                _translationDataTable.Columns["DefaultName"].ColumnName = defaultLanguage;
                GV.DataSource = _translationDataTable;
                EndProgress();
            };
            wrk.RunWorkerAsync(dbTreeview.CheckedObjects);
        }

        private void OnExcelExportClicked(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog {Filter = @"Excel Files (*.xls, *.xlsx)|*.xls;*.xlsx"};
            sfd.FileName = "Translation.xlsx";
            if (sfd.ShowDialog() != DialogResult.OK) return;

            XLWorkbook wb = new XLWorkbook();
            wb.Worksheets.Add(_translationDataTable, @"Translation");
            wb.SaveAs(sfd.FileName);
        }
    }
}

